import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:jump_scape/js_data/js_member.dart';
import 'package:jump_scape/js_ui/js_widget/js_image_view.dart';
import 'package:jump_scape/js_ui/js_widget/js_style.dart';

import '../../js_data/js_box/js_init.dart';
import '../../js_data/js_event.dart';
import '../../js_util/js_camare.dart';
import '../../objectbox.g.dart';
import '../js_dialog/js_loading.dart';
import '../js_dialog/js_personal_edit.dart';

class JsPersonalEditActivity extends StatefulWidget {
  static const url = 'personal_edit';
  const JsPersonalEditActivity({super.key});

  @override
  State<StatefulWidget> createState() => _JsPersonalEditActivity();
}

class _JsPersonalEditActivity extends State<JsPersonalEditActivity> {
  String _avatarUrlOld = "";
  String _nameOld = "";
  DateTime _birthDateOld = DateTime(1995, 1, 1, 00, 00, 00);
  String _countryNameOld = "";

  final TextEditingController _nameController = TextEditingController();
  String _avatarUrlNew = "";
  var _birthDateNew = DateTime(1995, 1, 1, 00, 00, 00);
  String _countryNameNew = "";

  @override
  void initState() {
    super.initState();
    JsEventManager.statPage(page: JsEventName.jsNameMineEdit);
    _init();
  }

  _init() async {
    final setting = await JsObjectBox.setting;
    var member = JsObjectBox.memberBox.query(MemberBox_.userId.equals(setting.userId)).build().findFirst();
    if (member != null) {
      _avatarUrlOld = member.avatarUrl;
      _nameOld = member.name;
      _birthDateOld = member.birth ?? DateTime(1995, 1, 1, 00, 00, 00);
      _countryNameOld = member.country;

      _avatarUrlNew = _avatarUrlOld;
      _nameController.text = _nameOld;
      _birthDateNew = _birthDateOld;
      _countryNameNew = _countryNameOld;

      if (mounted) {
        setState(() {});
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () => Future.value(false),
      child: Scaffold(
        body: Stack(
          children: [
            jsImage('assets/image/ic_records_bg.png', width: double.infinity, height: double.infinity, fit: BoxFit.cover),
            Padding(
              padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight),
              child: Row(
                children: [
                  InkWell(
                    onTap: () {
                      if (Navigator.canPop(context)) {
                        Navigator.pop(context);
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.fromLTRB(18.r, 15.r, 18.r, 0),
                      child: jsImage('assets/image/ic_finish.png', width: 64.r, height: 64.r),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              width: double.infinity,
              height: double.infinity,
              margin: EdgeInsets.fromLTRB(26.r, ScreenUtil().statusBarHeight + 40.r, 26.r, 0),
              clipBehavior: Clip.antiAlias,
              decoration: jsShapeRoundT(radius: 200.r, color: Colors.white),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    InkWell(
                      child: Stack(
                        children: [
                          Container(
                            width: 100.r,
                            height: 100.r,
                            margin: EdgeInsets.fromLTRB(5.r, 47.r, 5.r, 8.r),
                            clipBehavior: Clip.antiAlias,
                            decoration: jsShapeRound(radius: 50.r),
                            child: jsImage(_avatarUrlNew.isEmpty ? 'assets/image/ic_personal_edit_head.png' : _avatarUrlNew, fit: BoxFit.cover),
                          ),
                          Positioned(
                            right: 0,
                            bottom: 0,
                            child: jsImage('assets/image/ic_personal_edit_camera.png', width: 30.r, fit: BoxFit.fitWidth),
                          ),
                        ],
                      ),
                      onTap: () {
                        JsEventManager.statPage(page: JsEventName.jsNameEditavatar);

                        jsShowAvatarDialog(context, (index) {
                          if (index == 0 || index == 1) {
                            jsOpenCameraOrImage(
                              index == 0 ? ImageSource.gallery : ImageSource.camera,
                              (path) {
                                jsOpenCropImage(path).then((newPath) {
                                  if (newPath.isNotEmpty && newPath != _avatarUrlNew) {
                                    _avatarUrlNew = newPath;
                                    setState(() {});
                                  }
                                });
                              },
                              onCameraAccessDenied: () {
                                if (mounted) {
                                  jsShowRequiresCameraDialog(context);
                                }
                              },
                              onPhotoAccessDenied: () {
                                if (mounted) {
                                  jsShowRequiresPhotoDialog(context);
                                }
                              },
                            );
                          } else {
                            final newPath = 'assets/image/ic_personal_edit_head.png';
                            if (newPath.isNotEmpty && newPath != _avatarUrlNew) {
                              _avatarUrlNew = newPath;
                              setState(() {});
                            }
                          }
                        });
                      },
                    ),
                    Container(
                      height: 45.r,
                      padding: EdgeInsets.fromLTRB(13.r, 0, 0, 0),
                      margin: EdgeInsets.fromLTRB(18.r, 32.r, 18.r, 0),
                      decoration: jsShapeRound(radius: 10.r, color: Color(0xFFF9F9F9)),
                      child: Stack(
                        alignment: Alignment.centerLeft,
                        children: [
                          Text("Nick Name", style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Colors.black.withOpacity(0.3), fontSize: 14.r)),
                          TextField(
                            maxLength: 12,
                            controller: _nameController,
                            scrollPadding: const EdgeInsets.all(0),
                            textAlign: TextAlign.right,
                            textAlignVertical: TextAlignVertical.top,
                            cursorColor: Color(0xFF14C2F7),
                            cursorHeight: 14.r,
                            inputFormatters: [FilteringTextInputFormatter.deny(RegExp(r'[\n]'))],
                            onChanged: (value) {},
                            decoration: InputDecoration(
                              contentPadding: EdgeInsets.fromLTRB(0, 0, 13.r, 0),
                              hintText: "",
                              counterText: "",
                              hintStyle: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Color(0xFF404040), fontSize: 14.r),
                              border: InputBorder.none,
                              focusedBorder: InputBorder.none,
                              enabledBorder: InputBorder.none,
                            ),
                            style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Color(0xFF404040), fontSize: 14.r),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: double.infinity,
                      height: 45.r,
                      padding: EdgeInsets.fromLTRB(13.r, 0, 13.r, 0),
                      margin: EdgeInsets.fromLTRB(18.r, 30.r, 18.r, 0),
                      alignment: Alignment.centerLeft,
                      decoration: jsShapeRound(radius: 10.r, color: Color(0xFFF9F9F9)),
                      child: InkWell(
                        child: Container(
                          width: double.infinity,
                          height: double.infinity,
                          child: Row(
                            children: [
                              Text("Date of Birth", style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Colors.black.withOpacity(0.3), fontSize: 14.r)),
                              Spacer(),
                              Text(
                                "${_birthDateNew.year}-${_birthDateNew.month < 9 ? "0${_birthDateNew.month}" : _birthDateNew.month}-${_birthDateNew.day < 9 ? "0${_birthDateNew.day}" : _birthDateNew.day}",
                                style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Color(0xFF404040), fontSize: 14.r),
                              ),
                            ],
                          ),
                        ),
                        onTap: () {
                          final time = DateTime.now();

                          showDatePicker(
                            context: context,
                            initialDate: _birthDateNew,
                            firstDate: DateTime(1900),
                            lastDate: DateTime(time.year - 18),
                            confirmText: "Yes",
                            cancelText: "Cancel",
                            helpText: "Date of Birth",
                          ).then((value) {
                            if (value != null && !value.isAtSameMomentAs(_birthDateNew)) {
                              _birthDateNew = value;
                              setState(() {});
                            }
                          });
                        },
                      ),
                    ),
                    Container(
                      width: double.infinity,
                      height: 45.r,
                      padding: EdgeInsets.fromLTRB(13.r, 0, 13.r, 0),
                      margin: EdgeInsets.fromLTRB(18.r, 30.r, 18.r, 0),
                      alignment: Alignment.centerLeft,
                      decoration: jsShapeRound(radius: 10.r, color: Color(0xFFF9F9F9)),
                      child: InkWell(
                        child: Container(
                          width: double.infinity,
                          height: double.infinity,
                          child: Row(
                            children: [
                              Text("Country", style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Colors.black.withOpacity(0.3), fontSize: 14.r)),
                              Spacer(),
                              Text(_countryNameNew, style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Color(0xFF404040), fontSize: 14.r)),
                            ],
                          ),
                        ),
                        onTap: () {
                          jsShowCountryDialog(context, ((country) {
                            if (_countryNameNew != country) {
                              _countryNameNew = country;
                              setState(() {});
                            }
                          }));
                        },
                      ),
                    ),
                    Container(
                      height: 38.r,
                      margin: EdgeInsets.fromLTRB(62.r, 64.r, 62.r, 0),
                      clipBehavior: Clip.antiAlias,
                      decoration: jsShapeRound(radius: 12.r, shadows: [
                        BoxShadow(offset: Offset(1.r, 1.r), blurRadius: 4.r, color: Color(0xFFC9C9C9)),
                      ]),
                      child: InkWell(
                        child: Stack(
                          alignment: Alignment.center,
                          children: [
                            jsImage('assets/image/ic_personal_item.png', width: double.infinity, height: double.infinity, fit: BoxFit.fill),
                            Text("Submit", style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.white, fontSize: 18.r)),
                          ],
                        ),
                        onTap: () {
                          if (_nameController.text.trim().isEmpty) return;

                          jsShowLoadingDialog(context);

                          JsMember().saveMember(
                            avatarUrl: _avatarUrlNew,
                            nickname: _nameController.text,
                            birthday: _birthDateNew,
                            country: _countryNameNew,
                            onSuccess: (member) {
                              precacheImage(CachedNetworkImageProvider(member.avatarUrl), context);

                              Navigator.pop(context);
                              Navigator.pop(context, member);

                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                  content: Text('Edit successfully', style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.white, fontSize: 20.r)),
                                ),
                              );
                            },
                            onFailed: (msg) {
                              Navigator.pop(context);
                              if (msg.isNotEmpty) {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content: Text(msg, style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.white, fontSize: 20.r)),
                                  ),
                                );
                              }
                            },
                          );
                        },
                      ),
                    ),
                    SizedBox(height: 200.r),
                  ],
                ),
              ),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: IgnorePointer(
                child: jsImage('assets/image/ic_home_bg_bottom.png', width: double.infinity, fit: BoxFit.fitWidth),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
